package com.hy.web;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.hy.domain.Tour;

@Controller
public class HylvController {

	@RequestMapping("hylv")
	public String hylv(Model model, @RequestParam(defaultValue = "1", required = false) int page) {
		long count = Tour.countTours();
		int length = 5; // 读取条数
		int pages = (int) (count % length > 0 ? count / length + 1 : count
				/ length); // 总页数
		// 大于总页数，或者页码小于0，重定向到第一页
		if (page > pages || page < 1) {
			return "redirect:/hylv.html?page=1";
		}
		/*
		int up = page > 1 && page <= pages ? page - 1 : 1; // 上一页
		int next = page > 0 && page < pages ? page + 1 : 1; // 下一页
		int start = (int) (count - page * length); // 起始位置

		start = start < 0 ? 0 : start;
		length = start == 0 ? (int) count % length : length;
		List<Tour> tours = Tour.findTourEntries(start, length); 
		Collections.reverse(tours); // 降序排列
		*/
		
		int up = page > 1 && page <= pages ? page - 1 : 1; // 上一页
		int next = page > 0 && page < pages ? page + 1 : 1; // 下一页
		int start = (int) ((page - 1) * length); // 起始位置

		start = start < 0 ? 0 : start;
		List<Tour> tours = Tour.getTourOrderBySort(start, length); 

		model.addAttribute("tours", tours);
		model.addAttribute("pages", pages);
		model.addAttribute("up", up);
		model.addAttribute("next", next);
		model.addAttribute("page", page);
		return "hylv";
	}
	
	@RequestMapping("hylv_xq")
	public String hylvXq(Model model, @RequestParam long id) {
		/*
		Tour tour = Tour.findTour(id);
		if(null == tour){
			return "redirect:404";
		}
		model.addAttribute("tour", tour);
		model.addAttribute("up", tour.getUp());
		model.addAttribute("next", tour.getNext());
		return "hylv_xq";
		*/
		return "redirect:/hylv/view/" + id + ".html";
	}
	
}
